package com.xlzcx.xltz;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.xlzcx.xltz.utils.SnowFlakeUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Demo {
    public static void main(String[] args) {
        // 阿里云 OSS 配置
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";  // 修改为你的 OSS 访问域名
        String accessKeyId = "LTAI5tM88xx9GjQ1mhdvRkhj";  // 替换为你的 AccessKey ID
        String accessKeySecret = "Nxz5EfUowTqd5hYln4tbDv2GaQR436";  // 替换为你的 AccessKey Secret
        String bucketName = "item-kf";  // 替换为你的 OSS Bucket 名称

        String filePath = "E:\\文件\\图片\\2K\\jpg\\2k (15).jpg";  // 本地文件路径
        File file = new File(filePath);


        int dotIndex = file.getName().lastIndexOf('.');
        String substring = file.getName().substring(dotIndex + 1);
        long fileName = SnowFlakeUtil.getFlowIdInstance().nextId();
        String objectName = new SimpleDateFormat("yyyy/MM/dd/HH").format(new Date()) + "/" + fileName + "." + substring;  // 上传到 OSS 中的文件名


        // 创建 OSSClient 实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 上传文件到 OSS
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file);
            ossClient.putObject(putObjectRequest);
            System.out.println("文件上传成功!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("文件上传失败!");
        } finally {
            // 关闭 OSS 客户端
            ossClient.shutdown();
        }
    }
}
